import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

// 导入login的组件
const login = () =>
    import ('@/views/login/login.vue')

// 导入layout组件
const layout = () =>
    import ('@/layout/index.vue')

// 导入子路由
// 路由懒加载
const home = () =>
    import ('@/views/home')
const ask = () =>
    import ('@/views/ask')
const video = () =>
    import ('@/views/video')
const mine = () =>
    import ('@/views/mine')
const edit = () =>
    import ('@/views/mine/edit')
const articleNew = () =>
    import ('@/views/home/articleNew')
const search = () =>
    import ('@/views/serach/')
const result = () =>
    import ('@/views/serach/result')
const chat = () =>
    import ('@/views/mine/chat')

const routes = [

    { path: '', redirect: '/layout/home' },
    { name: 'login', path: '/login', component: login },
    { name: 'edit', path: '/mine/edit', component: edit, meta: { needLogin: true } },
    { name: 'articleNew', path: '/home/articleNew', component: articleNew },
    { name: 'search', path: '/search', component: search },
    { name: 'result', path: '/search/result', component: result },
    { name: 'chat', path: '/mine/chat', component: chat, meta: { needLogin: true } },

    {
        name: layout,
        path: '/layout',
        component: layout,
        children: [
            // 子路由可以不加/，代表先拼接父路由路径再访问
            { name: 'home', path: 'home', component: home, meta: { needKeep: true } },
            { name: 'ask', path: 'ask', component: ask },
            { name: 'video', path: 'video', component: video },
            { name: 'mine', path: 'mine', component: mine, meta: { needLogin: true } },
        ]
    },

]

const router = new VueRouter({
    routes
})

import store from '@/store'
import { Toast } from 'vant';


// 路由对象加全局前置守卫
// to：   去哪
// from:  从哪来
// next 是一个函数，调用它代表放行（跳转），不调用代表不放行（不跳转）
router.beforeEach((to, from, next) => {
    // 判断去的页面是不是需要登录的页面
    // 需要先给路由打上标签
    if (to.meta.needLogin) {
        // 证明是需要登录的页面 
        // 如何判断有没有登录？
        if (store.state.tokenObj.token) {
            next()
        } else {
            // 代表没登录，打回登录页
            // 页就是放行到登录页
            // 弹出一个轻提示
            Toast.fail('请先登录')

            // 除了打回登录页，还要记录一下原本想访问的页面是哪个路径
            // to就是我们原本想去的路由，因此打回登录页时，我们需要
            // 把原本要去的路由的路径记录下来,to.path就是原本想访问的路径
            // next的用法相当于是$router.push，所以也可以通过query传递参数
            next({
                name: 'login',
                query: {
                    back: to.path
                }
            })
        }
    } else {
        next()
    }
})

// 官方提供的解决办法：
// 解决放行到别的页面会报错的提醒
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
    if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
    return originalPush.call(this, location).catch(err => err)
}
export default router